package com.cnunicom.modules.addressbook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cnunicom.modules.addressbook.dao.ChinaDao;
import com.cnunicom.modules.addressbook.entity.ChinaEntity;
import com.cnunicom.modules.addressbook.service.ChinaService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author: dingziyuan
 * @Date: 2019/7/14 14:41
 * @Description: 省市区数据处理
 */
@Service("chinaService")
public class ChinaServiceImpl extends ServiceImpl<ChinaDao, ChinaEntity> implements ChinaService {

    private static Pattern COMPILE_PROVINCE = Pattern.compile("0000$");
    private static Pattern COMPILE_CITY = Pattern.compile("00$");
    private static Pattern COMPILE_AREA = Pattern.compile("[1-9]$");

    @Override
    public ArrayList<ChinaEntity> getChinaList() {

        List<ChinaEntity> list = this.list(new QueryWrapper<>());

        //先将省市区的数据区分出来,然后先将区的数据加到市里边,再将市的数据加到省里边.
        List<ChinaEntity> province = list.stream().filter(v -> COMPILE_PROVINCE.matcher(v.getId().toString()).find()).collect(Collectors.toList());
        List<ChinaEntity> city = list.stream().filter(v -> COMPILE_CITY.matcher(v.getId().toString()).find()).collect(Collectors.toList());
        List<ChinaEntity> area = list.stream().filter(v -> COMPILE_AREA.matcher(v.getId().toString()).find()).collect(Collectors.toList());

        return (ArrayList<ChinaEntity>) process(process(area, city), province);
    }



    /**
     * 省市区处理
     * @param lower
     * @param senior
     * @return
     */
    private List<ChinaEntity> process(List<ChinaEntity> lower, List<ChinaEntity> senior) {
        senior.forEach(s -> {
            List<ChinaEntity> free = new ArrayList<>();
            lower.forEach(l ->{
                if (s.getId().equals(l.getPid())) {
                    free.add(l);
                }
            });
            s.setChildren(free);
        });
        return senior;
    }
}
